package com.hwpt.chesedemo.presentation.screen

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.hwpt.chesedemo.presentation.viewmodel.TeachingUiState
import com.hwpt.chesedemo.presentation.viewmodel.TeachingViewModel
import com.hwpt.chesedemo.utils.FormattedResponseText

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TeachScreen(
    navController: NavController,
    viewModel: TeachingViewModel = hiltViewModel()
) {
    val uiState by viewModel.uiState.collectAsState()
    val configuration = LocalConfiguration.current
    val screenWidth = configuration.screenWidthDp.dp
    val screenHeight = configuration.screenHeightDp.dp

    val isPortrait = configuration.screenHeightDp > configuration.screenWidthDp
    val isSmallScreen = screenWidth < 600.dp
    val isTablet = screenWidth >= 600.dp && screenWidth < 840.dp
    val isLargeTablet = screenWidth >= 840.dp

    // 清理 ViewModel 资源
    LaunchedEffect(Unit) {
        // 如果需要，可以在这里执行一些一次性操作
    }

    Scaffold { innerPadding ->
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(
                    brush = Brush.verticalGradient(
                        colors = listOf(Color(0xFF6A11CB), Color(0xFF2575FC))
                    )
                )
                .padding(innerPadding)
        ) {
            if (uiState.showAIChat) {
                // AI聊天界面 - 自适应布局
                AdaptiveAIChatSection(
                    uiState = uiState,
                    onUserQuestionChange = viewModel::setUserQuestion,
                    onDropdownExpandedChange = viewModel::setDropdownExpanded,
                    onSendQuestion = viewModel::sendQuestion,
                    onClose = {
                        viewModel.resetChat()
                        viewModel.setShowAIChat(false)
                    },
                    chessQuestions = viewModel.chessQuestions,
                    isSmallScreen = isSmallScreen,
                    isTablet = isTablet,
                    isLargeTablet = isLargeTablet,
                    isPortrait = isPortrait
                )
            } else {
                // 规则教学内容 - 自适应布局
                AdaptiveRulesContentSection(
                    onAskAI = {
                        viewModel.setShowAIChat(true)
                    },
                    isSmallScreen = isSmallScreen,
                    isTablet = isTablet
                )
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AdaptiveAIChatSection(
    uiState: TeachingUiState,
    onUserQuestionChange: (String) -> Unit,
    onDropdownExpandedChange: (Boolean) -> Unit,
    onSendQuestion: () -> Unit,
    onClose: () -> Unit,
    chessQuestions: List<String>,
    isSmallScreen: Boolean,
    isTablet: Boolean,
    isLargeTablet: Boolean,
    isPortrait: Boolean
) {
    val horizontalPadding = when {
        isSmallScreen -> 16.dp
        isTablet -> 24.dp
        else -> 32.dp
    }

    val verticalPadding = when {
        isSmallScreen -> 16.dp
        isTablet -> 20.dp
        else -> 24.dp
    }

    if (isPortrait) {
        PortraitAIChatLayout(
            uiState = uiState,
            onUserQuestionChange = onUserQuestionChange,
            onDropdownExpandedChange = onDropdownExpandedChange,
            onSendQuestion = onSendQuestion,
            onClose = onClose,
            chessQuestions = chessQuestions,
            isSmallScreen = isSmallScreen,
            horizontalPadding = horizontalPadding,
            verticalPadding = verticalPadding
        )
    } else {
        LandscapeAIChatLayout(
            uiState = uiState,
            onUserQuestionChange = onUserQuestionChange,
            onDropdownExpandedChange = onDropdownExpandedChange,
            onSendQuestion = onSendQuestion,
            onClose = onClose,
            chessQuestions = chessQuestions,
            isSmallScreen = isSmallScreen,
            horizontalPadding = horizontalPadding,
            verticalPadding = verticalPadding
        )
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PortraitAIChatLayout(
    uiState: TeachingUiState,
    onUserQuestionChange: (String) -> Unit,
    onDropdownExpandedChange: (Boolean) -> Unit,
    onSendQuestion: () -> Unit,
    onClose: () -> Unit,
    chessQuestions: List<String>,
    isSmallScreen: Boolean,
    horizontalPadding: Dp,
    verticalPadding: Dp
) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(horizontal = horizontalPadding, vertical = verticalPadding),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        // 标题
        Text(
            text = "AI国际象棋助手",
            fontSize = when {
                isSmallScreen -> 24.sp
                else -> 32.sp
            },
            fontWeight = FontWeight.Bold,
            color = Color.White,
            textAlign = TextAlign.Center,
            modifier = Modifier.padding(bottom = if (isSmallScreen) 12.dp else 16.dp)
        )

        // 描述
        Text(
            text = "咨询国际象棋相关问题或自由提问",
            fontSize = when {
                isSmallScreen -> 14.sp
                else -> 16.sp
            },
            color = Color.White.copy(alpha = 0.9f),
            textAlign = TextAlign.Center,
            modifier = Modifier.padding(bottom = if (isSmallScreen) 16.dp else 24.dp)
        )

        // 关闭按钮
        Button(
            onClick = onClose,
            modifier = Modifier
                .fillMaxWidth(if (isSmallScreen) 0.8f else 0.6f)
                .height(if (isSmallScreen) 60.dp else 80.dp)
                .padding(bottom = if (isSmallScreen) 12.dp else 16.dp)
        ) {
            Text(
                text = "返回规则教学",
                fontSize = if (isSmallScreen) 14.sp else 16.sp
            )
        }

        // 常见问题下拉选择
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .padding(bottom = if (isSmallScreen) 12.dp else 16.dp)
        ) {
            Card(
                modifier = Modifier.fillMaxWidth(),
                colors = CardDefaults.cardColors(
                    containerColor = Color.White.copy(alpha = 0.15f)
                ),
                onClick = { onDropdownExpandedChange(true) }
            ) {
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(if (isSmallScreen) 12.dp else 16.dp),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = "选择常见问题",
                        color = Color.White,
                        fontSize = if (isSmallScreen) 14.sp else 16.sp
                    )
                    Icon(
                        imageVector = Icons.Default.ArrowDropDown,
                        contentDescription = "下拉箭头",
                        tint = Color.White
                    )
                }
            }

            DropdownMenu(
                expanded = uiState.isDropdownExpanded,
                onDismissRequest = { onDropdownExpandedChange(false) },
                modifier = Modifier.fillMaxWidth(if (isSmallScreen) 0.95f else 0.9f)
            ) {
                chessQuestions.forEach { question ->
                    DropdownMenuItem(
                        text = {
                            Text(
                                text = question,
                                fontSize = if (isSmallScreen) 12.sp else 14.sp,
                                modifier = Modifier.padding(4.dp)
                            )
                        },
                        onClick = {
                            onUserQuestionChange(question)
                            onDropdownExpandedChange(false)
                        }
                    )
                }
            }
        }

        // 自定义问题输入框
        TextField(
            value = uiState.userQuestion,
            onValueChange = onUserQuestionChange,
            modifier = Modifier
                .fillMaxWidth()
                .height(if (isSmallScreen) 80.dp else 100.dp),
            placeholder = {
                Text(
                    "请输入您的问题，或从上方选择常见问题...",
                    color = Color.White.copy(alpha = 0.7f),
                    fontSize = if (isSmallScreen) 12.sp else 14.sp
                )
            },
            colors = TextFieldDefaults.colors(
                focusedTextColor = Color.White,
                unfocusedTextColor = Color.White,
                focusedContainerColor = Color.White.copy(alpha = 0.15f),
                unfocusedContainerColor = Color.White.copy(alpha = 0.15f),
                focusedIndicatorColor = Color.White,
                unfocusedIndicatorColor = Color.White.copy(alpha = 0.5f),
                cursorColor = Color.White,
                focusedPlaceholderColor = Color.White.copy(alpha = 0.7f),
                unfocusedPlaceholderColor = Color.White.copy(alpha = 0.7f)
            ),
            singleLine = false,
            maxLines = 3
        )

        Spacer(modifier = Modifier.height(if (isSmallScreen) 16.dp else 24.dp))

        // 发送按钮
        Button(
            onClick = onSendQuestion,
            modifier = Modifier
                .fillMaxWidth(if (isSmallScreen) 0.9f else 0.8f)
                .height(if (isSmallScreen) 48.dp else 56.dp),
            enabled = !uiState.isLoading && uiState.userQuestion.isNotBlank()
        ) {
            if (uiState.isLoading) {
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.Center
                ) {
                    CircularProgressIndicator(
                        color = Color.White,
                        strokeWidth = 2.dp,
                        modifier = Modifier.size(if (isSmallScreen) 16.dp else 20.dp)
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(
                        text = if (uiState.isStreamComplete) "处理中..." else "AI思考中...",
                        fontSize = if (isSmallScreen) 14.sp else 18.sp,
                        fontWeight = FontWeight.Medium
                    )
                }
            } else {
                Text(
                    text = "发送问题",
                    fontSize = if (isSmallScreen) 14.sp else 18.sp,
                    fontWeight = FontWeight.Medium
                )
            }
        }

        Spacer(modifier = Modifier.height(if (isSmallScreen) 24.dp else 40.dp))

        // 结果显示区域
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .weight(1f),
            colors = CardDefaults.cardColors(
                containerColor = Color.White.copy(alpha = 0.15f)
            ),
            shape = MaterialTheme.shapes.medium
        ) {
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(if (isSmallScreen) 12.dp else 20.dp)
            ) {
                if (uiState.isLoading || uiState.response.isNotEmpty()) {
                    Column(
                        modifier = Modifier
                            .fillMaxSize()
                            .verticalScroll(rememberScrollState()),
                        horizontalAlignment = Alignment.Start
                    ) {
                        Text(
                            text = "AI回复：",
                            fontSize = if (isSmallScreen) 16.sp else 18.sp,
                            fontWeight = FontWeight.Bold,
                            color = Color.White,
                            modifier = Modifier.padding(bottom = if (isSmallScreen) 12.dp else 16.dp)
                        )

                        if (uiState.isLoading && uiState.response.isEmpty()) {
                            Box(
                                modifier = Modifier.fillMaxSize(),
                                contentAlignment = Alignment.Center
                            ) {
                                Column(
                                    horizontalAlignment = Alignment.CenterHorizontally
                                ) {
                                    CircularProgressIndicator(color = Color.White)
                                    Spacer(modifier = Modifier.height(12.dp))
                                    Text(
                                        text = "AI正在思考中...",
                                        color = Color.White.copy(alpha = 0.8f),
                                        fontSize = if (isSmallScreen) 12.sp else 14.sp
                                    )
                                }
                            }
                        } else {
                            FormattedResponseText(
                                response = uiState.response,
                                isStreamComplete = uiState.isStreamComplete,
                                isLoading = uiState.isLoading
                            )
                        }
                    }
                } else {
                    Column(
                        modifier = Modifier.fillMaxSize(),
                        horizontalAlignment = Alignment.CenterHorizontally,
                        verticalArrangement = Arrangement.Center
                    ) {
                        Text(
                            text = "输入您的问题或选择常见问题开始对话",
                            fontSize = if (isSmallScreen) 12.sp else 14.sp,
                            color = Color.White.copy(alpha = 0.7f),
                            textAlign = TextAlign.Center
                        )

                        Spacer(modifier = Modifier.height(12.dp))

                        Text(
                            text = "💡 使用提示：\n• 可以从上方选择常见问题\n• 也可以输入任何国际象棋相关问题\n• AI会为您提供专业的解答",
                            fontSize = if (isSmallScreen) 10.sp else 12.sp,
                            color = Color.White.copy(alpha = 0.6f),
                            textAlign = TextAlign.Start,
                            lineHeight = if (isSmallScreen) 16.sp else 18.sp
                        )
                    }
                }
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun LandscapeAIChatLayout(
    uiState: TeachingUiState,
    onUserQuestionChange: (String) -> Unit,
    onDropdownExpandedChange: (Boolean) -> Unit,
    onSendQuestion: () -> Unit,
    onClose: () -> Unit,
    chessQuestions: List<String>,
    isSmallScreen: Boolean,
    horizontalPadding: Dp,
    verticalPadding: Dp
) {
    Row(
        modifier = Modifier
            .fillMaxSize()
            .padding(horizontal = horizontalPadding, vertical = verticalPadding)
    ) {
        // 左侧：输入区域
        Column(
            modifier = Modifier
                .weight(1f)
                .fillMaxHeight(),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Text(
                text = "AI国际象棋助手",
                fontSize = if (isSmallScreen) 20.sp else 24.sp,
                fontWeight = FontWeight.Bold,
                color = Color.White,
                textAlign = TextAlign.Center,
                modifier = Modifier.padding(bottom = 12.dp)
            )

            Button(
                onClick = onClose,
                modifier = Modifier
                    .fillMaxWidth()
                    .height(if (isSmallScreen) 48.dp else 56.dp)
                    .padding(bottom = 16.dp)
            ) {
                Text("返回规则教学")
            }

            // 常见问题下拉选择
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 12.dp)
            ) {
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    colors = CardDefaults.cardColors(
                        containerColor = Color.White.copy(alpha = 0.15f)
                    ),
                    onClick = { onDropdownExpandedChange(true) }
                ) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(12.dp),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            text = "选择常见问题",
                            color = Color.White,
                            fontSize = if (isSmallScreen) 12.sp else 14.sp
                        )
                        Icon(
                            imageVector = Icons.Default.ArrowDropDown,
                            contentDescription = "下拉箭头",
                            tint = Color.White
                        )
                    }
                }

                DropdownMenu(
                    expanded = uiState.isDropdownExpanded,
                    onDismissRequest = { onDropdownExpandedChange(false) },
                    modifier = Modifier.fillMaxWidth(0.95f)
                ) {
                    chessQuestions.forEach { question ->
                        DropdownMenuItem(
                            text = {
                                Text(
                                    text = question,
                                    fontSize = if (isSmallScreen) 11.sp else 12.sp,
                                    modifier = Modifier.padding(4.dp)
                                )
                            },
                            onClick = {
                                onUserQuestionChange(question)
                                onDropdownExpandedChange(false)
                            }
                        )
                    }
                }
            }

            // 自定义问题输入框
            TextField(
                value = uiState.userQuestion,
                onValueChange = onUserQuestionChange,
                modifier = Modifier
                    .fillMaxWidth()
                    .weight(1f),
                placeholder = {
                    Text(
                        "请输入您的问题...",
                        color = Color.White.copy(alpha = 0.7f),
                        fontSize = if (isSmallScreen) 12.sp else 14.sp
                    )
                },
                colors = TextFieldDefaults.colors(
                    focusedTextColor = Color.White,
                    unfocusedTextColor = Color.White,
                    focusedContainerColor = Color.White.copy(alpha = 0.15f),
                    unfocusedContainerColor = Color.White.copy(alpha = 0.15f),
                    focusedIndicatorColor = Color.White,
                    unfocusedIndicatorColor = Color.White.copy(alpha = 0.5f),
                    cursorColor = Color.White,
                    focusedPlaceholderColor = Color.White.copy(alpha = 0.7f),
                    unfocusedPlaceholderColor = Color.White.copy(alpha = 0.7f)
                ),
                singleLine = false,
                maxLines = 10
            )

            Spacer(modifier = Modifier.height(12.dp))

            Button(
                onClick = onSendQuestion,
                modifier = Modifier
                    .fillMaxWidth()
                    .height(if (isSmallScreen) 44.dp else 48.dp),
                enabled = !uiState.isLoading && uiState.userQuestion.isNotBlank()
            ) {
                if (uiState.isLoading) {
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.Center
                    ) {
                        CircularProgressIndicator(
                            color = Color.White,
                            strokeWidth = 2.dp,
                            modifier = Modifier.size(16.dp)
                        )
                        Spacer(modifier = Modifier.width(6.dp))
                        Text(
                            text = if (uiState.isStreamComplete) "处理中..." else "AI思考中...",
                            fontSize = if (isSmallScreen) 12.sp else 14.sp
                        )
                    }
                } else {
                    Text(
                        text = "发送问题",
                        fontSize = if (isSmallScreen) 12.sp else 14.sp
                    )
                }
            }
        }

        Spacer(modifier = Modifier.width(16.dp))

        // 右侧：结果显示区域
        Card(
            modifier = Modifier
                .weight(1.5f)
                .fillMaxHeight(),
            colors = CardDefaults.cardColors(
                containerColor = Color.White.copy(alpha = 0.15f)
            )
        ) {
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(16.dp)
            ) {
                if (uiState.isLoading || uiState.response.isNotEmpty()) {
                    Column(
                        modifier = Modifier
                            .fillMaxSize()
                            .verticalScroll(rememberScrollState()),
                        horizontalAlignment = Alignment.Start
                    ) {
                        Text(
                            text = "AI回复：",
                            fontSize = if (isSmallScreen) 16.sp else 18.sp,
                            fontWeight = FontWeight.Bold,
                            color = Color.White,
                            modifier = Modifier.padding(bottom = 12.dp)
                        )

                        if (uiState.isLoading && uiState.response.isEmpty()) {
                            Box(
                                modifier = Modifier.fillMaxSize(),
                                contentAlignment = Alignment.Center
                            ) {
                                Column(
                                    horizontalAlignment = Alignment.CenterHorizontally
                                ) {
                                    CircularProgressIndicator(color = Color.White)
                                    Spacer(modifier = Modifier.height(12.dp))
                                    Text(
                                        text = "AI正在思考中...",
                                        color = Color.White.copy(alpha = 0.8f),
                                        fontSize = if (isSmallScreen) 12.sp else 14.sp
                                    )
                                }
                            }
                        } else {
                            FormattedResponseText(
                                response = uiState.response,
                                isStreamComplete = uiState.isStreamComplete,
                                isLoading = uiState.isLoading
                            )
                        }
                    }
                } else {
                    Column(
                        modifier = Modifier.fillMaxSize(),
                        horizontalAlignment = Alignment.CenterHorizontally,
                        verticalArrangement = Arrangement.Center
                    ) {
                        Text(
                            text = "输入问题开始对话",
                            fontSize = if (isSmallScreen) 12.sp else 14.sp,
                            color = Color.White.copy(alpha = 0.7f),
                            textAlign = TextAlign.Center
                        )
                    }
                }
            }
        }
    }
}

@Composable
fun AdaptiveRulesContentSection(
    onAskAI: () -> Unit,
    isSmallScreen: Boolean,
    isTablet: Boolean
) {
    val horizontalPadding = when {
        isSmallScreen -> 16.dp
        isTablet -> 20.dp
        else -> 24.dp
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .verticalScroll(rememberScrollState())
            .padding(horizontal = horizontalPadding, vertical = 16.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        // 标题
        Text(
            text = "国际象棋规则教学",
            fontSize = when {
                isSmallScreen -> 24.sp
                isTablet -> 28.sp
                else -> 32.sp
            },
            fontWeight = FontWeight.Bold,
            color = Color.White,
            textAlign = TextAlign.Center,
            modifier = Modifier.padding(bottom = if (isSmallScreen) 12.dp else 16.dp)
        )

        // 描述
        Text(
            text = "学习国际象棋的基本规则和策略",
            fontSize = when {
                isSmallScreen -> 14.sp
                else -> 16.sp
            },
            color = Color.White.copy(alpha = 0.9f),
            textAlign = TextAlign.Center,
            modifier = Modifier.padding(bottom = if (isSmallScreen) 16.dp else 24.dp)
        )

        // 询问AI按钮
        Button(
            onClick = onAskAI,
            modifier = Modifier
                .fillMaxWidth(if (isSmallScreen) 0.9f else 0.8f)
                .height(if (isSmallScreen) 60.dp else 80.dp)
                .padding(bottom = if (isSmallScreen) 16.dp else 24.dp)
        ) {
            Text(
                text = "🤖 询问AI相关问题",
                fontSize = if (isSmallScreen) 14.sp else 16.sp
            )
        }

        // 棋盘与棋子介绍
        AdaptiveRuleSection(
            title = "♟️ 棋盘与棋子",
            content = "国际象棋棋盘为8×8的方格，共64个格子，深浅相间。对局开始时，双方各有16个棋子：",
            isSmallScreen = isSmallScreen
        ) {
            AdaptivePieceItem(
                icon = "♔",
                name = "王 (King)",
                description = "每方1个，最重要的棋子",
                isSmallScreen = isSmallScreen
            )
            AdaptivePieceItem(
                icon = "♕",
                name = "后 (Queen)",
                description = "每方1个，威力最大的棋子",
                isSmallScreen = isSmallScreen
            )
            AdaptivePieceItem(
                icon = "♖",
                name = "车 (Rook)",
                description = "每方2个，沿直线移动",
                isSmallScreen = isSmallScreen
            )
            AdaptivePieceItem(
                icon = "♗",
                name = "象 (Bishop)",
                description = "每方2个，沿斜线移动",
                isSmallScreen = isSmallScreen
            )
            AdaptivePieceItem(
                icon = "♘",
                name = "马 (Knight)",
                description = "每方2个，走\"日\"字",
                isSmallScreen = isSmallScreen
            )
            AdaptivePieceItem(
                icon = "♙",
                name = "兵 (Pawn)",
                description = "每方8个，只能向前移动",
                isSmallScreen = isSmallScreen
            )
        }

        // 棋子走法
        AdaptiveRuleSection(
            title = "🚶 棋子走法",
            content = "",
            isSmallScreen = isSmallScreen
        ) {
            AdaptiveRuleItem("王：每次可以朝任何方向移动一格，但不能走到被攻击的位置。", isSmallScreen)
            AdaptiveRuleItem("后：可以朝任何方向移动任意格数，但不能越过其他棋子。", isSmallScreen)
            AdaptiveRuleItem(
                "车：可以沿水平或垂直方向移动任意格数，但不能越过其他棋子。",
                isSmallScreen
            )
            AdaptiveRuleItem("象：可以沿斜线方向移动任意格数，但不能越过其他棋子。", isSmallScreen)
            AdaptiveRuleItem(
                "马：走\"日\"字，可以跳过其他棋子，是唯一能越过其他棋子的棋子。",
                isSmallScreen
            )
            AdaptiveRuleItem(
                "兵：只能向前移动。第一步可以选择移动一格或两格，之后每次只能移动一格。吃子时，兵斜向前进一格吃子。",
                isSmallScreen
            )
        }

        // 特殊规则
        AdaptiveRuleSection(
            title = "⚡ 特殊规则",
            content = "",
            isSmallScreen = isSmallScreen
        ) {
            AdaptiveSpecialRule(
                title = "王车易位 (Castling)",
                description = "一局棋中，双方各有一次机会同时移动王和车。王向一侧车的方向移动两格，然后车越过王放在王的相邻格。条件：王和参与易位的车都未曾移动过；王没有被将军；王经过和到达的格子没有被对方攻击。",
                isSmallScreen = isSmallScreen
            )
            AdaptiveSpecialRule(
                title = "吃过路兵 (En Passant)",
                description = "当一方兵从初始位置一步前进两格时，如果刚好落在对方兵的旁边，对方兵可以立即斜进一格吃掉这个兵，就像它只前进了一格一样。",
                isSmallScreen = isSmallScreen
            )
            AdaptiveSpecialRule(
                title = "兵的升变 (Promotion)",
                description = "当兵到达对方底线时，必须升变为后、车、象或马中的任意一种，但不能变王，也不能不变。",
                isSmallScreen = isSmallScreen
            )
        }

        // 胜负判定
        AdaptiveRuleSection(
            title = "🏆 胜负判定",
            content = "",
            isSmallScreen = isSmallScreen
        ) {
            AdaptiveRuleItem(
                "将死 (Checkmate)：当一方的王被将军且无法避免被吃掉时，游戏结束，对方获胜。",
                isSmallScreen
            )
            AdaptiveRuleItem("认输 (Resignation)：一方可以主动认输。", isSmallScreen)
            AdaptiveRuleItem("超时 (Time Out)：在计时比赛中，一方时间用完。", isSmallScreen)
            AdaptiveRuleItem(
                "和棋 (Draw)：包括双方同意和棋、三次重复局面、五十步规则、逼和（一方未被将军但无合法着法）等。",
                isSmallScreen
            )
        }

        Spacer(modifier = Modifier.height(if (isSmallScreen) 24.dp else 40.dp))
    }
}

@Composable
fun AdaptiveRuleSection(
    title: String,
    content: String,
    isSmallScreen: Boolean,
    contentBlock: @Composable () -> Unit
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = if (isSmallScreen) 6.dp else 8.dp),
        colors = CardDefaults.cardColors(
            containerColor = Color.White.copy(alpha = 0.15f)
        )
    ) {
        Column(
            modifier = Modifier.padding(if (isSmallScreen) 12.dp else 20.dp)
        ) {
            Text(
                text = title,
                fontSize = if (isSmallScreen) 16.sp else 20.sp,
                fontWeight = FontWeight.Bold,
                color = Color.White,
                modifier = Modifier.padding(bottom = if (isSmallScreen) 8.dp else 12.dp)
            )

            if (content.isNotEmpty()) {
                Text(
                    text = content,
                    fontSize = if (isSmallScreen) 12.sp else 16.sp,
                    color = Color.White.copy(alpha = 0.9f),
                    lineHeight = if (isSmallScreen) 18.sp else 24.sp,
                    modifier = Modifier.padding(bottom = if (isSmallScreen) 8.dp else 12.dp)
                )
            }

            contentBlock()
        }
    }
}

@Composable
fun AdaptivePieceItem(icon: String, name: String, description: String, isSmallScreen: Boolean) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = if (isSmallScreen) 2.dp else 4.dp),
        colors = CardDefaults.cardColors(
            containerColor = Color.White.copy(alpha = 0.1f)
        )
    ) {
        Row(
            modifier = Modifier.padding(if (isSmallScreen) 8.dp else 12.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = icon,
                fontSize = if (isSmallScreen) 18.sp else 24.sp,
                modifier = Modifier
                    .width(if (isSmallScreen) 30.dp else 40.dp)
                    .padding(end = if (isSmallScreen) 8.dp else 12.dp),
                textAlign = TextAlign.Center
            )
            Column {
                Text(
                    text = name,
                    fontSize = if (isSmallScreen) 12.sp else 16.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color.White
                )
                Text(
                    text = description,
                    fontSize = if (isSmallScreen) 10.sp else 14.sp,
                    color = Color.White.copy(alpha = 0.8f),
                    lineHeight = if (isSmallScreen) 14.sp else 16.sp
                )
            }
        }
    }
}

@Composable
fun AdaptiveRuleItem(text: String, isSmallScreen: Boolean) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = if (isSmallScreen) 2.dp else 4.dp)
    ) {
        Text(
            text = "•",
            fontSize = if (isSmallScreen) 12.sp else 16.sp,
            color = Color.White.copy(alpha = 0.8f),
            modifier = Modifier.padding(horizontal = if (isSmallScreen) 6.dp else 8.dp)
        )
        Text(
            text = text,
            fontSize = if (isSmallScreen) 12.sp else 16.sp,
            color = Color.White.copy(alpha = 0.9f),
            lineHeight = if (isSmallScreen) 16.sp else 22.sp,
            modifier = Modifier.weight(1f)
        )
    }
}

@Composable
fun AdaptiveSpecialRule(title: String, description: String, isSmallScreen: Boolean) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = if (isSmallScreen) 4.dp else 6.dp),
        colors = CardDefaults.cardColors(
            containerColor = Color.White.copy(alpha = 0.1f)
        )
    ) {
        Column(
            modifier = Modifier.padding(if (isSmallScreen) 12.dp else 16.dp)
        ) {
            Text(
                text = title,
                fontSize = if (isSmallScreen) 14.sp else 16.sp,
                fontWeight = FontWeight.Bold,
                color = Color.White,
                modifier = Modifier.padding(bottom = if (isSmallScreen) 6.dp else 8.dp)
            )
            Text(
                text = description,
                fontSize = if (isSmallScreen) 11.sp else 14.sp,
                color = Color.White.copy(alpha = 0.8f),
                lineHeight = if (isSmallScreen) 16.sp else 20.sp
            )
        }
    }
}